package com.example.demo.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.mapper.ClickHouse.ClickHouseMapper;
import com.example.demo.mapper.FundAccountMapper;
import com.example.demo.mapper.StockPositionsMapper;
import com.example.demo.pojo.Accounts.FundAccounts;
import com.example.demo.pojo.R;
import com.example.demo.pojo.Stock.Stock;
import com.example.demo.pojo.Stock.StockPositions;
import com.example.demo.service.StockInfoService;
import com.example.demo.utils.StockPositionsUtils;
import com.example.demo.utils.TokenUtil.decryptToken;
import com.example.demo.utils.TokenUtil.spiltUtils;
import com.example.demo.utils.UserUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class StockInfoServiceImpl extends ServiceImpl<StockPositionsMapper, StockPositions> implements StockInfoService {

    @Resource
    private StockPositionsMapper stockPositionsMapper;

    @Resource
    private FundAccountMapper fundAccountMapper;

    @Resource
    private UserUtil userUtil;

    private ClickHouseMapper clickHouseMapper;

    private StockPositionsUtils stockPositionsUtils;

    @Override
    public R<List<StockPositions>> GetDynamicInformation(String token) {
        //获取当前用户的id
        String decrypt = decryptToken.decrypt(token);
        String userName = spiltUtils.getUserName(decrypt);
        Integer userId = userUtil.getUserId(userName);
        // 查询获取一个用户当前所有的持仓信息
        QueryWrapper<StockPositions> stockPositionsQueryWrapper = new QueryWrapper<>();
        stockPositionsQueryWrapper.eq("user_id", userId);
        List<StockPositions> stockPositionsList = stockPositionsMapper.selectList(stockPositionsQueryWrapper);
        // 对每一张订单表,获取最新市场价,然后更新信息
        // 第一次循环 StockPositions列表,先更新最新价,市值,并将总市值累加
        // 新的持仓总市值
        BigDecimal marketValueSum = null;
        // 新的总盈亏
        BigDecimal positionProfitLossSum = null;
        for (StockPositions stockPositions : stockPositionsList) {
            String stockCode = stockPositions.getStockCode();
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String now = LocalDateTime.now().format(df);
            Stock stock = clickHouseMapper.getStockInfo(stockCode,LocalDateTime.now());
            // 获取最新市场价
            BigDecimal marketPrice = stock.getLast().setScale(2, RoundingMode.HALF_UP);
            // 更新市场价
            stockPositions.setLatestPrice(marketPrice);
            // 更新市值
            BigDecimal marketValue = marketPrice
                    .multiply(BigDecimal.valueOf(stockPositions.getAvailableQuantity()))
                    .setScale(2, RoundingMode.HALF_UP);
            stockPositions.setMarketValue(marketValue);
            assert false;
            marketValueSum = marketValueSum.add(marketValue);
            // 计算盈亏,市场价减成本价再乘以持仓数量
            BigDecimal positionProfitLoss = marketPrice
                    .subtract(stockPositions.getCostPrice())
                    .multiply(BigDecimal.valueOf(stockPositions.getAvailableQuantity()))
                    .setScale(2, RoundingMode.HALF_UP);
            stockPositions.setPositionProfitLoss(positionProfitLoss);
            positionProfitLossSum = positionProfitLossSum.add(positionProfitLoss);
            // 更新盈亏比例 当前盈亏/成本价*持仓数量
            stockPositions.setProfitLossRatio(positionProfitLoss
                    .divide(
                            stockPositions.getCostPrice().multiply(BigDecimal.valueOf(stockPositions.getAvailableQuantity())),
                            2, // 结果保留的小数位数
                            RoundingMode.HALF_UP // 舍入模式
                    )
            );
        }
        // 获取此用户的FundAccounts表并进行更新
        // QueryWrapper<FundAccounts> fundAccountsQueryWrapper = new QueryWrapper<>();
        // fundAccountsQueryWrapper.eq("user_id",userid);
        FundAccounts fundAccounts = fundAccountMapper.selectById(userId);
        // 获取当前可用资金
        BigDecimal availableFund = fundAccounts.getAvailableFund();
        // 更新总资产
        fundAccounts.setTotalAsset(availableFund.add(marketValueSum).setScale(2, RoundingMode.HALF_UP));
        // 更新持仓市值
        fundAccounts.setPositionValue(marketValueSum.setScale(2, RoundingMode.HALF_UP));
        // 更新总盈亏
        fundAccounts.setPositionProfitLoss(positionProfitLossSum.setScale(2, RoundingMode.HALF_UP));

        // 第二次循环,更新StockPositions列表中的持仓比例
        for (StockPositions stockPositions : stockPositionsList) {
            BigDecimal marketValue = stockPositions.getMarketValue();
            // 持仓比例 = 当前个股市值/总市值
            stockPositions.setPositionRatio(marketValue.multiply(marketValueSum).setScale(2, RoundingMode.HALF_UP));
        }
        return R.success(stockPositionsList);
    }

    @Override
    public R<FundAccounts> GetAllDynamicInformation(String token) {
        //获取当前用户的id
        String decrypt = decryptToken.decrypt(token);
        String userName = spiltUtils.getUserName(decrypt);
        Integer userId = userUtil.getUserId(userName);
        // 查询获取一个用户当前所有的持仓信息
        QueryWrapper<StockPositions> stockPositionsQueryWrapper = new QueryWrapper<>();
        stockPositionsQueryWrapper.eq("user_id", userId);
        List<StockPositions> stockPositionsList = stockPositionsMapper.selectList(stockPositionsQueryWrapper);
        // 对每一张订单表,获取最新市场价,然后更新信息
        // 第一次循环 StockPositions列表,先更新最新价,市值,并将总市值累加
        // 新的持仓总市值
        BigDecimal marketValueSum = null;
        // 新的总盈亏
        BigDecimal positionProfitLossSum = null;
        for (StockPositions stockPositions : stockPositionsList) {
            String stockCode = stockPositions.getStockCode();
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String now = LocalDateTime.now().format(df);
            Stock stock = clickHouseMapper.getStockInfo(stockCode, LocalDateTime.now());
            // 获取最新市场价
            BigDecimal marketPrice = stock.getLast().setScale(2, RoundingMode.HALF_UP);
            // 更新市场价
            stockPositions.setLatestPrice(marketPrice);
            // 更新市值
            BigDecimal marketValue = marketPrice
                    .multiply(BigDecimal.valueOf(stockPositions.getAvailableQuantity()))
                    .setScale(2, RoundingMode.HALF_UP);
            stockPositions.setMarketValue(marketValue);
            assert false;
            marketValueSum = marketValueSum.add(marketValue);
            // 计算盈亏,市场价减成本价再乘以持仓数量
            BigDecimal positionProfitLoss = marketPrice
                    .subtract(stockPositions.getCostPrice())
                    .multiply(BigDecimal.valueOf(stockPositions.getAvailableQuantity()))
                    .setScale(2, RoundingMode.HALF_UP);
            stockPositions.setPositionProfitLoss(positionProfitLoss);
            positionProfitLossSum = positionProfitLossSum.add(positionProfitLoss);
            // 更新盈亏比例 当前盈亏/成本价*持仓数量
            stockPositions.setProfitLossRatio(positionProfitLoss
                    .divide(stockPositions.getCostPrice()
                            .multiply(BigDecimal.valueOf(stockPositions.getAvailableQuantity())), 2, RoundingMode.HALF_UP));
        }
        // 获取此用户的FundAccounts表并进行更新
        // QueryWrapper<FundAccounts> fundAccountsQueryWrapper = new QueryWrapper<>();
        // fundAccountsQueryWrapper.eq("user_id",userid);
        FundAccounts fundAccounts = fundAccountMapper.selectById(userId);
        // 获取当前可用资金
        BigDecimal availableFund = fundAccounts.getAvailableFund();
        // 更新总资产
        fundAccounts.setTotalAsset(availableFund.add(marketValueSum).setScale(2, RoundingMode.HALF_UP));
        // 更新持仓市值
        fundAccounts.setPositionValue(marketValueSum.setScale(2, RoundingMode.HALF_UP));
        // 更新总盈亏
        fundAccounts.setPositionProfitLoss(positionProfitLossSum.setScale(2, RoundingMode.HALF_UP));

        // 第二次循环,更新StockPositions列表中的持仓比例
        for (StockPositions stockPositions : stockPositionsList) {
            BigDecimal marketValue = stockPositions.getMarketValue();
            // 持仓比例 = 当前个股市值/总市值
            stockPositions.setPositionRatio(marketValue.multiply(marketValueSum).setScale(2, RoundingMode.HALF_UP));
        }
        return R.success(fundAccounts);
    }
}
